using CriWare;
using IQIGame.Onigao.Framework;
using System;
#if UNITY_EDITOR
#endif

namespace IQIGame.Onigao.Game
{
    public class CriAudioSource : IDisposable
    {
        CriAtomSource m_source;

        public CriAtomSource Source => m_source;

        public CriAudioSource(CriAtomSource source)
        {
            m_source = source;
            m_source.use3dPositioning = true;
        }

        public AudioPlayback PlayAudio(string cueName, string cueSheetName, AudioSourceType sourceType)
        {
            _ = ManagerCenter.Audio.GetOrAddCueSheet(cueSheetName, sourceType);

            m_source.cueSheet = cueSheetName;
            m_source.cueName = cueName;
            var playback = m_source.Play();

            var pb = ClassPool.Get<AudioPlayback>();
            pb.Initialize(playback, m_source);
            ManagerCenter.Audio.AddPlayback(pb);

            return pb;
        }

        public AudioPlayback PlayAudioWithLabel(string cueName, string cueSheetName, AudioSourceType sourceType, string selector, string label)
        {
            _ = ManagerCenter.Audio.GetOrAddCueSheet(cueSheetName, sourceType);

            bool hasSelectorLabel = !string.IsNullOrEmpty(selector) && !string.IsNullOrEmpty(label);
            if (sourceType == AudioSourceType.BgmSource)
            {
                // bgm模式下。如果cue和sheet一样，并且有selector和label，就不用重新播，刷新label就行了。
                if (hasSelectorLabel && m_source.cueSheet == cueSheetName && m_source.cueName == cueName)
                {
                    SetSelectorLabel(selector, label);
                    return null;
                }
            }
            m_source.cueSheet = cueSheetName;
            m_source.cueName = cueName;
            if (hasSelectorLabel)
            {
                m_source.player.SetSelectorLabel(selector, label);
            }
            var playback = m_source.Play();

            var pb = ClassPool.Get<AudioPlayback>();
            pb.Initialize(playback, m_source);
            ManagerCenter.Audio.AddPlayback(pb);

            return pb;
        }
        
        public void StopSource()
        {
            // 停止播放的情况下，清除cueName，防止下次播放时，因为cueName相同，并且使用SelectorLabel，导致不播放的问题。
            m_source.cueName = string.Empty;

            m_source.Stop();
            ManagerCenter.Audio.RemovePlayBack(m_source);
        }

        //sw	true: 暂停, false: 继续播放
        public void PauseSource(bool sw)
        {
            m_source.Pause(sw);
        }

        public void SetSelectorLabel(string selector, string label)
        {
            m_source.player.SetSelectorLabel(selector, label);
            m_source.player.UpdateAll();
        }

        public void SetAisacControl(string controlName, float value)
        {
            m_source.SetAisacControl(controlName, value);
        }

        public void Dispose()
        {
            m_source.Stop();
            UnityEngine.Object.Destroy(m_source);
        }
    }
}
